<template>
  <ag-popup
    v-model="layerVisible"
    :title="title"
    confirm
    confirmVal="保存"
    cancel
    cancelVal="取消"
    @onConfirm="onConfirm"
    @onCancel="onCancel"
    class="popup-box my-popup-box"
  >
    <div class="stylePanle" ref="styleItemBox" @click="handleClick">
      <div class="styleContent">
        <textarea class="contentDiv vscroll" v-model="styleJson"></textarea>
        <button
          class="ant-btn ant-btn-primary ant-btn-sm btn-newstyle"
          @click="formatJson"
        >
          格式化
        </button>
        <button
          class="ant-btn ant-btn-primary ant-btn-sm btn-newstyle"
          @click="saveAsNewStyle()"
        >
          另存为新样式
        </button>
        <button
          class="ant-btn ant-btn-primary ant-btn-sm btn-application"
          @click="application()"
        >
          应用
        </button>
      </div>
      <div class="styleItem vscroll">
        <div
          v-for="item in jsonData"
          :key="item.id"
          class="list"
          @click="handleTypeClick(item)"
          @contextmenu.prevent="openSetMenu($event, item)"
        >
          <div class="img" :title="item.name">
            <img v-if="item.img" :src="item.img" width="100%" height="100%" />
            <p style="line-height: 70px;color:#fff">暂无图片</p>
          </div>
          <!-- v-if="item.name != curStyleObj.name" -->
          <div class="title">
            {{ item.name }}
          </div>
          <!-- <input
            v-if="item.name == curStyleObj.name"
            type="text"
            v-model="item.name"
            class="titleIpt"
            @blur="update()"
          /> -->
        </div>
      </div>
      <!-- 右键菜单 -->
      <div class="rt-menu-box" ref="rtMenuBox" v-show="isRtMenuShow">
        <ul>
          <li
            v-for="item in rtMenuList"
            :key="item.key"
            @click="handleMemuEvent(item.key)"
          >
            <span>{{ item.name }}</span>
          </li>
        </ul>
      </div>
    </div>
  </ag-popup>
</template>
<script>
var  axiosWraper = agcim.net.axiosWraper
var  axios = agcim.net.http;
import canvas2Image from "@/views/js/extension/canvas2Image.js";
import AgPopup from "@/views/components/precut/AgPopup.vue";
import indexP from "./js/index";
let primitives = [];
let NormalWaterStyle = agcim.renderer.PrimitiveStyle.NormalWaterStyle;
let waterPrimitiveStyle = undefined;
export default {
  components: {
    "ag-popup": AgPopup,
  },
  data() {
    return {
      disabled: true,
      curStyleObj: {},
      layerVisible: false,
      styleJson: "",
      // 样式列表
      jsonData: [],
      //右键菜单是否显示
      isRtMenuShow: false,
      //右键菜单列表
      rtMenuList: [
        // { index: "0", name: "重命名", key: "updateName", popconfirm: false },
        {
          index: "1",
          name: "更新缩略图",
          key: "updateThumbnail",
          popconfirm: true,
        },
        { index: "2", name: "删除", key: "delete", popconfirm: true },
      ],
      layer: {},
    };
  },
  mounted() {
    //监听工具栏的图层树的变化，当触发
    this.$on("LayerStyle", o => {
      this.display(o)
    });
  },
  methods: {
    ondisabled() {
      this.disabled = false;
    },
    async getStyleConfigList() {
      this.jsonData = [];
      let name = this.layer.text.indexOf("水域") > -1 ? "水域" : "";
      let res = await axiosWraper.getData(
        agcim.net.apiPath.styleConfig_find,
        {
          page: 1,
          rows: 1000,
          name: name,
          layerType: this.layer.layerType,
        }
      );
      if (res.success) {
        let arr = this.apiFieldConvert(res.content.rows);
        for (let i = 0; i < arr.length; i++) {
          let o = arr[i];
          //现在前端改转义的字符
		      o.information = decodeURIComponent(o.information);
          o.information = o.information.replaceAll("INVALID", ")");
          o.information = o.information.replaceAll("&gt;", ">");
          o.information = o.information.replaceAll("&lt;", "<");
          if (
            o.viewImg &&
            o.viewImg.indexOf(";base64,") == -1 &&
            o.viewImg !== "null"
          ) {
            o.img = "data:image/png;base64," + arr[i].viewImg;
          } else {
            if (o.viewImg === "null") {
              o.img = false;
            } else {
              o.img = arr[i].viewImg;
            }
          }
          this.jsonData.push(o);
        }
      }
    },
    //将接口字段替换成当前使用的字段
    apiFieldConvert(list){
      let listConvert = [];
      list.forEach(ele => {
        let item = {
          ...ele,
          id: ele.styleMgrId,
          name: ele.styleMgrName,
          information: ele.styleMgrInfo,
          remark: ele.styleMgrRemark
        }
        listConvert.push(item)
      });
      return listConvert;
    },
    display(node) {
      this.layerVisible = true;
      this.layer = node;
      this.getStyleConfigList();
      // var arr = CIM.viewer.scene.primitives._primitives;
      this.curLayer = [];
      // for (let j = 0; j < arr.length; j++) {
      //   let o = arr[j].agMetaData;
      //   if (o && o.id === this.layer.id) {
      //     this.curLayer.push(arr[j]);
      //   }
      // }
      if (this.layer && this.layer.layerType) {
        let layerId = this.layer.id;
        CIM.layerTree._aglayers.forEach((item) => {
          if (item.id === layerId) {
            this.curLayer.push(item);
          }
        });
      }
    },
    onConfirm() {
      this.curStyleObj.layerId = this.layer.id;
      this.update("2");
    },
    onCancel() {
      this.layerVisible = false;
    },
    handleClick(e) {
      this.isRtMenuShow = false;
      let classItem = e.target.getAttribute("class");
      if (classItem && classItem.indexOf("styleItem") !== -1) {
      }
    },
    handleTypeClick(item) {
      this.curStyleObj = item;
      this.styleJson = item.information;
      this.isRtMenuShow = false;
    },
    // 另存为新样式
    async saveAsNewStyle() {
      let genimg = canvas2Image.capturePng(CIM.viewer, "200");
      var param = new FormData();
      param.append("styleMgrName", "新建_" + this.layer.text);
      param.append("layerType", this.layer.layerType);
      param.append("styleMgrInfo", this.styleJson);
      param.append("viewImg", genimg.src);

      let res = await axios.post(
        agcim.net.apiPath.styleConfig_add,
        param
      );
      if (res.success) {
        this.getStyleConfigList();
      }
    },
    delHtmlTag(str) {
      return str
        .replace(/<[^>]+>/g, "")
        .replace(/&nbsp;/g, "")
        .replace("var style =", "")
        .replace("var style = ", "")
        .replace(/&gt;/g, ">"); //去掉所有的html标记
    },
    application() {
      let v = this.styleJson;
      //每次应用之前先把样式修改为最初的样式
      if (v.indexOf("{") == 0) {
        let tileStyle = null;
        let glslIndex = v.indexOf("GLSL:");
        let glslSrc = null;
        if (glslIndex < 0) {
          tileStyle = JSON.parse(v);
        } else {
          tileStyle = JSON.parse(v.substr(0, glslIndex));
          glslSrc = v.substr(glslIndex + 5);
        }
        for (var i = 0; i < this.curLayer.length; i++) {
          if (this.curLayer[i] instanceof agcim.layer.Ag3DTilesLayer) {
            indexP.setCustomShader(this.curLayer[i]._primitives[0], "origin");
            if(tileStyle) this.curLayer[i].setStyle(tileStyle);
          } else if(this.curLayer[i] instanceof agcim.layer.WFSLayer){
            let baseWaterColor = JSON.parse(v).NormalWaterStyle.baseWaterColor;
            if(!(baseWaterColor.includes("#") || baseWaterColor.includes("rgb") || baseWaterColor.includes("rgba"))){
              baseWaterColor = eval(baseWaterColor)
            }
            //先移除掉旧的primitive
            if(primitives.length>=0){
              primitives.forEach((v) => {
                this.curLayer[i].removePrimitive(v);
              })
            }
            if(this.curLayer[i]._primitives.length>0){
              this.curLayer[i]._primitives.forEach(primitive=>{
                this.curLayer[i].removePrimitive(primitive);
              })
            }
            let entities = this.curLayer[i]._dataSource[0].entities.values;
            let primitivePositionsObject = this.getPrimitiveCartesianPositions(entities);
            // primitivePositionsObject.type = "polygon"
            if(waterPrimitiveStyle){
              waterPrimitiveStyle.dispose();
            }
            waterPrimitiveStyle  = new NormalWaterStyle({
              isGround:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.isGround,false),
              frequency:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.frequency,3000),
              animationSpeed:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.animationSpeed,0.01),
              amplitude:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.amplitude,3),
              specularIntensity:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.specularIntensity,1),
              extrudedHeight:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.extrudedHeight,50),
              alpha:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.alpha,1.0),
              baseWaterColor:baseWaterColor,
              waterNormalMap:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.waterNormalMap,Cesium.buildModuleUrl("Assets/Textures/waterNormals.jpg")),
              repeatX:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.repeatX,1.0),
              repeatY:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.repeatY,1.0),
              flowdirection:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.flowdirection,5.0),
              flowSpeed:Cesium.defaultValue(JSON.parse(v).NormalWaterStyle.flowSpeed,1.0),
            });
            this.curLayer[i]._dataSource[0].show = false;
            waterPrimitiveStyle.addPrimitve(this.curLayer[i],primitivePositionsObject.primitive);
          }
        }
        if (glslSrc) {
          indexP.setCustomShader(this.curLayer[0]._primitives[0], glslSrc);
        }
      } else {
        //动态光
        this.curLayer[0].style = null;
        indexP.setCustomShader(this.curLayer[0]._primitives[0], v);
      }
    },
    getPrimitiveCartesianPositions(entities) {
      //先支持线、面
      let primitivePositionsObject = {};
      let primitivePositions = [];
      for (let i = 0; i < entities.length; i++) {
        if(entities[i].polygon){
          if(!primitivePositionsObject.type){primitivePositionsObject.type = "polygon";}
          let hierarchy = entities[i].polygon.hierarchy._value;
          let positions = hierarchy.positions;
          let holes = hierarchy.holes;
          let PolygonHierarchys = [];
          if (holes.length > 0) {
            for (let j = 0; j < holes.length; j++) {
              PolygonHierarchys.push(
                new Cesium.PolygonHierarchy(holes[j].positions)
              );
            }
          }
          primitivePositions.push({positions:positions,holes:PolygonHierarchys});
        }else if(entities[i].polyline){
          if(!primitivePositionsObject.type){primitivePositionsObject.type = "polyline";}
          primitivePositions.push(entities[i].polyline._positions._value) 
        }
      }
      primitivePositionsObject.primitive = primitivePositions;
      return primitivePositionsObject;
    },
    openSetMenu(e, item) {
      this.getMenuPosition(e);
      this.curItem = item;
    },
    //确定菜单位置
    getMenuPosition: function (event) {
      this.isRtMenuShow = true;
      this.$refs.rtMenuBox.style.left = event.clientX + "px";
      this.$refs.rtMenuBox.style.top = event.clientY + "px";
    },
    // 点击右键列事件
    handleMemuEvent(key) {
      this.isRtMenuShow = false;
      this[key]();
    },
    //修改
    async update(paramType = 1) {
      this.curStyleObj.styleMgrInfo = this.styleJson;
      this.disabled = true;
      var param = new FormData();
      for (let i in this.curStyleObj) {
        if (i == "createTime" || i == "modifyTime") {
          param.append(i, "");
        } else {
          param.append(i, this.curStyleObj[i]);
        }
      }
      param.append("paramType", paramType);
      let res = await axios.post(
        agcim.net.apiPath.styleConfig_update,
        param
      );
      if (res.success) {
        this.getStyleConfigList();
        this.$message.success("修改成功");
      }
    },
    updateName() {
      this.disabled = false;
    },
    // 更新缩略图
    updateThumbnail() {
      let genimg = canvas2Image.capturePng(CIM.viewer, "200");
      this.curStyleObj.viewImg = genimg.src;
      this.update();
    },
   // 删除
   delete() {
      let vm = this;
      this.$confirm('确认删除？删除不可恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning',
        center: true,
      }).then(async () => {
        let res = await axios.post(
          agcim.net.apiPath.styleConfig_delete + `?ids=` +
          vm.curStyleObj.id
        );
        if (res.success) {
          vm.$message.success("删除成功");
          vm.getStyleConfigList();
        }
      }).catch(() => {
        // vm.$message.success('取消');
      });
    },
    formatJson() {
      if (this.styleJson) {
        var tt = JSON.stringify(JSON.parse(this.styleJson), null, "\t");
        this.styleJson = tt;
      }
    },
  },
  computed: {
    title: function () {
      return "图层样式 - " + this.layer.nameCn;
    },
  },
};
</script>
<style scoped>
.popup-box {
  width: 650px;
  top: 50%;
}
.my-popup-box {
  top: 50%;
}
.stylePanle {
  width: 650px;
  height: 250px;
  border-bottom: 1px solid #ccc;
}
.styleContent {
  width: 310px;
  height: 250px;
  padding: 5px;
  float: left;
}
.contentDiv {
  width: 300px;
  height: 200px;
  color: #fff;
  background: rgba(212, 211, 211, 0.3);
  overflow-y: auto;
}
.contentDiv code {
  font-size: 12px;
}
.styleItem {
  width: 330px;
  height: 200px;
  display: inline-block;
  overflow-y: auto;
  position: relative;
}
.styleItem .list {
  width: 80px;
  /* height: 100px; */
  padding: 5px;
  cursor: pointer;
  float: left;
}
.styleItem .list .img {
  width: 70px;
  height: 70px;
  border: 1px solid #fff;
  border-radius: 2px;
  overflow: hidden;
  text-align: center;
}
.styleItem .list .img:hover {
  border: 1px solid #fcf;
}
.styleItem .list .title,
.styleItem .list .titleIpt {
  color: #fff;
  width: 70px;
  text-align: center;
  /* white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all; */
}
.styleItem .list .titleIpt {
  border: none;
  background: rgba(0, 0, 0, 0.05);
}
/* 菜单树右侧鼠标菜单 */
.rt-menu-box {
  position: fixed;
  z-index: 90;
  min-width: 120px;
  background-color: rgba(255, 255, 255, 0.9);
  -webkit-box-shadow: 0px 1px 15px 1px rgba(69, 65, 78, 0.18);
  box-shadow: 0px 1px 15px 1px rgba(69, 65, 78, 0.18);
}

.rt-menu-box ul {
  padding: 10px 0;
  margin: 0;
}

.rt-menu-box li {
  list-style-type: none;
}

.rt-menu-box span {
  display: block;
  color: #595959;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  /* font-family: inherit; */
  background: #fff;
  border: 0px;
  border-radius: 1px;
  padding: 0 30px;
}

.rt-menu-box span:hover {
  color: #fff;
  background: #36a3f7;
  cursor: pointer;
}

.rt-menu-box span i {
  margin-right: 10px;
}
.styleContent button {
  margin: 10px 5px 0px 5px;
}
</style>